using System;
using System.Collections.Generic;
using System.Text;

namespace Multiplicity.Reflection {
    public class TypeDef : TypeInfo {

        readonly Module module;
        readonly string name;
        readonly string namespc;
        readonly FieldInfo[] fields;

        internal TypeDef(Module module, uint index) {
            MetadataTable<TypeDefRow> table = module.Tables.TypeDef;
            TypeDefRow row = table[index];
            TypeDefRow nextRow = (index < (table.Count - 1)) ? table[index + 1] : null;
            
            this.module = module;
            this.name = module.Strings[row.NameIndex];
            this.namespc = module.Strings[row.NamespaceIndex];
            this.fields = ReadFields(row, nextRow);

        }

        public Module Module { get { return module; } }

        public override string Name {
            get { return name; }
        }

        public override string Namespace {
            get { return namespc; }
        }

        public override FieldInfo[] GetFields() {
            return fields;
        }

        FieldInfo[] ReadFields(TypeDefRow row, TypeDefRow nextRow) {
            uint fieldStart = row.FieldList;
            uint fieldCount = (nextRow == null) ? module.Tables.Fields.Count + 1 : nextRow.FieldList;

            fieldCount -= fieldStart;

            FieldInfo[] fi = new FieldInfo[fieldCount];
            for (uint i = 0; i < fieldCount; i++) {
                fi[i] = new FieldInfo(this, fieldStart + i - 1);
            }

            return fi;
        }
    }
}
